import React, { useState, useEffect } from 'react';
import {
  Button,
  Table,
  Space,
  Tag,
  message,
  Modal,
  Form,
  Select,
  Input,
  Drawer,
  Descriptions,
  List,
  Image,
  Typography,
  Divider
} from 'antd';
import {
  EyeOutlined,
  EditOutlined,
  SearchOutlined
} from '@ant-design/icons';
import './OrderManage.css';
import { useRequest } from 'ahooks';
import { getOrders, updateOrders } from '../../api/dashboard'; 

const { Option } = Select;
const { TextArea } = Input;

const OrderManage = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [searchText, setSearchText] = useState('');


  const { runAsync: fetchOrders } = useRequest(getOrders, {
    manual:true
  })
  const { runAsync: updateOrder } = useRequest(updateOrders, { manual: true });

  const fetchData = async () => {
    try {
       setLoading(true);

      const storedOrders = await fetchOrders({params:{id: localStorage.getItem('adminUser')?.id || '1' }});
      // 按照创建时间降序排序
      const sortedOrders = storedOrders.sort((a, b) => {
        return new Date(b.createTime) - new Date(a.createTime);
      });

      setOrders(sortedOrders);
      setLoading(false);
    }catch(err) {
      console.error('Error fetching orders:', err);
      setLoading(false);
      message.error('获取订单数据失败，请稍后重试');
    }
   
  };

  // 获取订单数据
  useEffect(() => {
    fetchData();
  }, []);

  // 获取订单状态标签颜色
  const getStatusColor = (status) => {
    switch (status) {
      case 'pending':
        return '#fa8c16'; // 橙色 - 待付款
      case 'paid':
        return '#1677ff'; // 蓝色 - 待发货
      case 'shipped':
        return '#722ed1'; // 紫色 - 待收货
      case 'completed':
        return '#52c41a'; // 绿色 - 已完成
      case 'cancelled':
        return '#ff4d4f'; // 红色 - 已取消
      default:
        return '#d9d9d9'; // 灰色 - 默认
    }
  };

  // 获取订单状态文本
  const getStatusText = (status) => {
    switch (status) {
      case 'pending':
        return '待付款';
      case 'paid':
        return '待发货';
      case 'shipped':
        return '待收货';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  // 表格列定义
  const columns = [
    {
      title: '订单号',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      filteredValue: [searchText],
      onFilter: (value, record) =>
        record.id.toString().toLowerCase().includes(value.toLowerCase())
    },
    {
      title: '用户信息',
      dataIndex: 'address',
      key: 'user',
      render: (address) => (
        <div>
          <div>{address?.name}</div>
          <div>{address?.phone}</div>
        </div>
      )
    },
    {
      title: '订单金额',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      render: (price) => `¥${price.toFixed(2)}`,
      sorter: (a, b) => a.totalPrice - b.totalPrice
    },
    {
      title: '商品数量',
      dataIndex: 'totalCount',
      key: 'totalCount',
      width: 90
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
      filters: [
        { text: '待付款', value: 'pending' },
        { text: '待发货', value: 'paid' },
        { text: '待收货', value: 'shipped' },
        { text: '已完成', value: 'completed' },
        { text: '已取消', value: 'cancelled' }
      ],
      onFilter: (value, record) => record.status === value
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      width: 100,
      render: (method) => {
        const methodText =
          method === 'alipay' ? '支付宝' :
            method === 'wechat' ? '微信支付' : '货到付款';
        return methodText;
      },
      filters: [
        { text: '支付宝', value: 'alipay' },
        { text: '微信支付', value: 'wechat' },
        { text: '货到付款', value: 'cod' }
      ],
      onFilter: (value, record) => record.paymentMethod === value
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text) => formatDate(text),
      sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime)
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          {record.status === 'paid' && (
            <Button
              type="primary"
              icon={<EditOutlined />}
              size="small"
              onClick={() => handleEdit(record)}
            >
              发货
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
  };

  // 查看订单详情
  const handleView = (record) => {
    setCurrentOrder(record);
    setDrawerVisible(true);
  };

  // 编辑订单（发货）
  const handleEdit = async (record) => {
    if (record.status !== 'paid') {
      message.warn('只能对已付款的订单进行发货操作');
      return;
    }
    try {
        const updatedOrders = await updateOrder([{
          id: editingId,
          ...record,
          status: 'shipped',
          shipTime: new Date().toISOString(),
        }]);
        setOrders(updatedOrders);
        message.success('订单已发货，物流信息已更新');
        setVisible(false);
      } catch (e) {
        message.error('发货失败');
      }
      setConfirmLoading(false);
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        setConfirmLoading(true);

        setTimeout(() => {
          // 更新订单
          const updatedOrders = orders.map(item => {
            if (item.id === editingId) {
              const now = new Date().toISOString();
              return {
                ...item,
                status: values.status,
                trackingNumber: values.trackingNumber,
                shipTime: now,
                shipRemark: values.remark
              };
            }
            return item;
          });

          setOrders(updatedOrders);
          localStorage.setItem('orders', JSON.stringify(updatedOrders));
          message.success('订单已发货，物流信息已更新');

          setVisible(false);
          setConfirmLoading(false);

          // 模拟发货后一段时间自动变为待收货状态
          setTimeout(() => {
            const finalOrders = JSON.parse(localStorage.getItem('orders') || '[]');
            const autoUpdatedOrders = finalOrders.map(item => {
              if (item.id === editingId && item.status === 'shipped') {
                message.info(`订单 ${item.id} 已送达，等待用户确认收货`);
                return item; // 保持shipped状态，等待用户确认收货
              }
              return item;
            });
            localStorage.setItem('orders', JSON.stringify(autoUpdatedOrders));
          }, 5000); // 5秒后提示送达
        }, 1000);
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };

  // 处理模态框取消
  const handleCancel = () => {
    setVisible(false);
  };

  // 处理抽屉关闭
  const handleDrawerClose = () => {
    setDrawerVisible(false);
  };

  return (
    <div className="order-manage">
      <div className="page-header">
        <h2>订单管理</h2>
        <div className="page-header-actions">
          <Button
            style={{ marginRight: 16 }}
            onClick={() => {
              // 创建一个测试订单用于验证流程
              const testOrder = {
                id: `TEST${Date.now()}`,
                orderItems: [{
                  id: 'test-product',
                  name: '测试商品',
                  price: 99.99,
                  image: 'https://via.placeholder.com/200x200/1677ff/ffffff?text=测试商品',
                  quantity: 1
                }],
                totalPrice: 99.99,
                totalCount: 1,
                address: {
                  name: '测试用户',
                  phone: '13800138000',
                  province: '广东省',
                  city: '深圳市',
                  district: '南山区',
                  address: '测试地址'
                },
                paymentMethod: 'alipay',
                status: 'paid',
                createTime: new Date().toISOString(),
                payTime: new Date().toISOString(),
                remark: '这是一个测试订单，用于验证确认收货流程'
              };

              const currentOrders = JSON.parse(localStorage.getItem('orders') || '[]');
              const newOrders = [testOrder, ...currentOrders];
              localStorage.setItem('orders', JSON.stringify(newOrders));
              setOrders(newOrders);
              message.success('已创建测试订单，可以进行发货和确认收货流程测试');
            }}
          >
            创建测试订单
          </Button>
          <Input
            placeholder="搜索订单号"
            prefix={<SearchOutlined />}
            style={{ width: 200 }}
            allowClear
            onChange={(e) => handleSearch(e.target.value)}
          />
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={orders}
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
      />

      {/* 发货表单 */}
      <Modal
        title="订单发货"
        open={visible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        confirmLoading={confirmLoading}
        maskClosable={false}
      >
        <Form
          form={form}
          layout="vertical"
          name="shipForm"
        >
          <Form.Item
            name="status"
            label="订单状态"
            initialValue="shipped"
            hidden
          >
            <Input readOnly />
          </Form.Item>

          <Form.Item
            name="trackingNumber"
            label="物流单号"
            rules={[{ required: true, message: '请输入物流单号' }]}
          >
            <Input placeholder="请输入物流单号" />
          </Form.Item>

          <Form.Item
            name="remark"
            label="发货备注"
          >
            <TextArea
              rows={4}
              placeholder="请输入发货备注（选填）"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 订单详情抽屉 */}
      <Drawer
        title="订单详情"
        placement="right"
        width={520}
        onClose={handleDrawerClose}
        open={drawerVisible}
      >
        {currentOrder && (
          <div className="order-detail">
            <Descriptions
              title="基本信息"
              bordered
              column={1}
              style={{ marginBottom: 20 }}
            >
              <Descriptions.Item label="订单号">{currentOrder.id}</Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusColor(currentOrder.status)}>
                  {getStatusText(currentOrder.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">¥{currentOrder.totalPrice.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {currentOrder.paymentMethod === 'alipay' ? '支付宝' :
                  currentOrder.paymentMethod === 'wechat' ? '微信支付' : '货到付款'}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{formatDate(currentOrder.createTime)}</Descriptions.Item>
              {currentOrder.payTime && (
                <Descriptions.Item label="支付时间">{formatDate(currentOrder.payTime)}</Descriptions.Item>
              )}
              {currentOrder.shipTime && (
                <Descriptions.Item label="发货时间">{formatDate(currentOrder.shipTime)}</Descriptions.Item>
              )}
              {currentOrder.completionTime && (
                <Descriptions.Item label="完成时间">{formatDate(currentOrder.completionTime)}</Descriptions.Item>
              )}
              {currentOrder.cancelTime && (
                <Descriptions.Item label="取消时间">{formatDate(currentOrder.cancelTime)}</Descriptions.Item>
              )}
              {currentOrder.trackingNumber && (
                <Descriptions.Item label="物流单号">{currentOrder.trackingNumber}</Descriptions.Item>
              )}
              {currentOrder.remark && (
                <Descriptions.Item label="订单备注">{currentOrder.remark}</Descriptions.Item>
              )}
              {currentOrder.shipRemark && (
                <Descriptions.Item label="发货备注">{currentOrder.shipRemark}</Descriptions.Item>
              )}
            </Descriptions>

            <Divider orientation="left">收货信息</Divider>
            {currentOrder.address && (
              <Descriptions bordered column={1} style={{ marginBottom: 20 }}>
                <Descriptions.Item label="收货人">{currentOrder.address.name}</Descriptions.Item>
                <Descriptions.Item label="联系电话">{currentOrder.address.phone}</Descriptions.Item>
                <Descriptions.Item label="收货地址">
                  {`${currentOrder.address.province}${currentOrder.address.city}${currentOrder.address.district}${currentOrder.address.address}`}
                </Descriptions.Item>
              </Descriptions>
            )}

            <Divider orientation="left">商品信息</Divider>
            <List
              itemLayout="horizontal"
              dataSource={currentOrder.orderItems}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Image width={50} src={item.image} />}
                    title={item.name}
                    description={`单价: ¥${item.price.toFixed(2)} × ${item.quantity}`}
                  />
                  <div>¥{(item.price * item.quantity).toFixed(2)}</div>
                </List.Item>
              )}
            />
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default OrderManage; 